<template>
  <div>
    <el-row :gutter="10">
      <el-col :sm="17" :lg="17">
        <div class="div-canvas">
           <div class="full-size" id="map-container"></div>
        </div>
      </el-col>

      <el-col :sm="7" :lg="7">
        <!-- <div style="float: left; width: 100%;height: 35%;background-color: aliceblue;text-align: left;">
          <el-collapse v-model="activeName" accordion>
            <el-collapse-item title="参数设置" name="1">
              <div m >
                中心纬度：<el-input-number :precision="2" :step="0.1" :max="10" size="small" />
                <br /> <br />
                中心经度：<el-input-number :precision="2" :step="0.1" :max="10" size="small" />
                <br /> <br />
                地图类型：<el-input class="w-50 m-2" size="small" style="width: 120px;" placeholder="Please Input"/> 
                <br /> <br />
                缩放级别：<el-input class="w-50 m-2" size="small" style="width: 120px;" placeholder="Please Input"/> 
                <br /> <br />
                更多设置：<el-input class="w-50 m-2" size="small" style="width: 120px;" placeholder="Please Input"/>  <br />
              </div>
            </el-collapse-item>
            <el-collapse-item title="校准设置" name="2">
              <div>
                Operation feedback: enable the users to clearly perceive their
                operations by style updates and interactive effects;
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>  -->
        
       
        <div style="float: left; width: 100%;height: 50%;text-align: left;" >
           <!-- <el-form :model="queryParams" label-position="right" inline ref="queryRef" v-show="showSearch" @submit.prevent>
            <el-form-item label="防区名称" prop="ip"> --> 
          <br />
          地图信息设置  
          <br />
          <br />
            雷达地址：
          <el-select clearable v-model="this.queryParams.id" @change="handleselect" style="width: 275px;">
            <el-option v-for="dict in this.radarOptions" :key="dict.id" :label="dict.ip" :value="dict.id"  />
          </el-select>
          <br />
          <br />
          雷达位置：
          <el-input-number v-model="this.queryParams.radarLat" :min="0" :max="360" controls-position="right" @change="handleChangeLan" style="width: 130px;" />
          - 
          <el-input-number v-model="this.queryParams.radarLon" :min="0" :max="360" controls-position="right" @change="handleChangeLon" style="width: 130px;" />
          <br />
          <br />
          波束角度：
          <br />
          <el-slider v-model="this.queryParams.angle" @change="changeAngle" show-input  />
          <br />
           波束半径：<br />
          <el-slider v-model="this.queryParams.radius" @change="changeRadius" show-input max="1000" />   
          <br />
          北偏角：<br />
          <el-slider v-model="this.queryParams.northDeviationAngle" @change="changeDirection" show-input max="360" />   
        </div>

        <div class="tool-box">
           <el-table :data="tableData" height="390" style="width: 100%" >
            <el-table-column prop="id" width="100" label="报警时间" />
            <el-table-column prop="areaName" width="100" label="报警防区" />
            <el-table-column prop="dateTime" label="跟踪相机" />
          </el-table>
        </div>
        <!-- 
        <div style="float: left; width: 100%;height: 30%;background-color:brown;">        
        </div> -->
      </el-col>
    </el-row>
  </div>
</template>

    
<script>

  import { listRadar, addRadar, delRadar, updateRadar, getRadar } from '@/api/device/radar'
  import { listAlarmRef } from '@/api/alarm/alarm_index'
  import { ref } from 'vue';
  import L from 'leaflet';
  import 'leaflet/dist/leaflet.css';
  import "@geoman-io/leaflet-geoman-free";
  import "@geoman-io/leaflet-geoman-free/dist/leaflet-geoman.css";

  import  Radar  from 'leaflet-radar';
  import 'leaflet.motion/dist/leaflet.motion.js';    
  import * as signalR from "@microsoft/signalr";


  import { listDrawPolygon,addDrawPolygon, updateDrawPolygon, delDrawPolygon, getDrawPolygon } from '@/api/map/map'
  import { el } from 'element-plus/es/locales.mjs';


  var seqGroup=null;
  
  var trackRoute=null; //json目标数据 
  var lat=0;
  var lng=0;
  var radius=0;
  var azimuthAngle=0;
  var angle=0;
  var step=0;

  //地图类型数据
  
  var mapUrl='./public/maptile_gaode/{z}/{x}/{y}.jpg';
  

  export default {
    name: "SignalR",
    components: {},

    

    data() {
      return {

        mapCenter_lat:ref(0),
        mapCenter_lng:ref(0),
        mapZoom:ref(15),

        map:null,
        timer: null,
        seqGroups:[],
        his_seqGroups:[],

        seqGroup:null,
        his_seqGroup:null,
        value : ref(0),
        
        activeName  : ref('1'),

        //新目标处理
        currSeqGroups:[],
        hisSeqGroups:[],

        // 长链接数据接口
        longLinkApi: 'http://localhost:5197/hubs/stock',
        // 长链接接受数据
        longLinkMsg: 'ReceiveTargetData',
        longLinkSendMsg: 'ReceiveTargetData',
        serverData:[],

        // 查询参数
        defenceareaOptions :[],
        
        y_Id  : ref(0),

        queryParams: {
          pageNum: 1,
          pageSize: 10,
          sort: 'id',
          sortType: 'asc',
          ip: undefined
        },

        tableData : [],
        
        form: {
          drawId: 0,
          defenceAreaId:0,
          pointListLatLng:'',
          status:1
        },

        drawPolygon:[],

        //Radar扇形图和扇形图集合
        radarDevice:null,
        radarDevices:[],
        
        radarDraw:
        {
          radius: 500,//探测距离
          angle:60,
          northDeviationAngle:90, //旋转角度
          lat:28.202616,
          lng:112.894302,
          step:4
        },

        radarOptions:ref([]),

        // radarLat :ref(0),
        // radarLon :ref(0),
        
      };
    },
    created () {
      this.handall();
      this.getList();
      this.init(this.connection,this.longLinkApi,this.longLinkMsg,this.longLinkSendMsg)
    },
    mounted() {   
      this.initDrawPolygon();
      this.initMap();
      
      this.clear_Target();
      this.clear_HisTarget();
    },
    methods: {
      getList() {
        listAlarmRef(this.queryParams).then(res => {
          if (res.data.code == 200) {
            this.tableData = res.data.data
          }
        })
      },
      handleselect()
      {        
        var tt= this.radarOptions.find(item => item.id === this.queryParams.id);
        this.queryParams.angle=tt.defenceAngle;
        this.queryParams.radius=tt.defenceRadius;
        this.queryParams.northDeviationAngle=tt.northDeviationAngle;
        this.queryParams.radarLat=tt.latitude;
        this.queryParams.radarLon=tt.longitude;
        this.y_Id=this.queryParams.id;
      },
      changeAngle(newValue){
        this.radarDevices.forEach((item, i) => {
          this.map.removeLayer(item);
        });
        this.radarDevices=[];

        var tt= this.radarOptions.find(item => item.id === this.queryParams.id);
        tt.defenceAngle=newValue;

        updateRadar(tt).then((response) => {
          this.handall();
        })
      },
      changeRadius(newValue){
        this.radarDevices.forEach((item, i) => {
          this.map.removeLayer(item);
        });
        this.radarDevices=[];

        var tt= this.radarOptions.find(item => item.id === this.queryParams.id);
        tt.defenceRadius=newValue;

        updateRadar(tt).then((response) => {
          this.handall();
        })      
      }, 
      changeDirection(newValue){
        this.radarDevices.forEach((item, i) => {
          this.map.removeLayer(item);
        });
        this.radarDevices=[];

        var tt= this.radarOptions.find(item => item.id === this.queryParams.id);
        tt.northDeviationAngle=newValue;

        updateRadar(tt).then((response) => {
          this.handall();
        })      
      },
      handleChangeLan(newValue)
      {       
        this.radarDevices.forEach((item, i) => {
          this.map.removeLayer(item);
        });
        this.radarDevices=[];

        var tt= this.radarOptions.find(item => item.id === this.queryParams.id);
        tt.latitude=newValue;

        updateRadar(tt).then((response) => {
          this.handall();
        })   
      },   
      handleChangeLon(newValue)
      {       
          //number | undefined
        this.radarDevices.forEach((item, i) => {
          this.map.removeLayer(item);
        });
        this.radarDevices=[];

        var tt= this.radarOptions.find(item => item.id === this.queryParams.id);
        tt.longitude=newValue;

        updateRadar(tt).then((response) => {
          this.handall();
        }) 
      },
      handall() {
        listRadar().then((response) => {
          this.radarOptions = response.data.data;

          if(this.y_Id!=''){
              this.queryParams.id =this.y_Id;
          }else{
            this.queryParams.id = this.radarOptions[0].id;
            this.y_Id=this.radarOptions[0].id;
          }
    
          var tt= this.radarOptions.find(item => item.id === this.queryParams.id);

          this.queryParams.angle=tt.defenceAngle;
          this.queryParams.radius=tt.defenceRadius;
          this.queryParams.northDeviationAngle=tt.northDeviationAngle;
          this.queryParams.radarLat=tt.latitude;
          this.queryParams.radarLon=tt.longitude;

          for (let item of this.radarOptions) {
            this.radarDraw.radius= item.defenceRadius,//探测距离
            this.radarDraw.angle=item.defenceAngle,
            this.radarDraw.northDeviationAngle=item.northDeviationAngle, //旋转角度
            this.radarDraw.lat=item.latitude,
            this.radarDraw.lng=item.longitude,
            this.radarDraw.step=4  
           

            this.initRadar();
          }    
        })
      },
      initMap() {

        this.getConfigKey('mapCenter').then((response) => {
          var ss=response.data.data.split(',')
          var newLatLng = L.latLng(parseFloat(ss[0]),parseFloat(ss[1]));
          this.map.setView(newLatLng);
        })
        
        this.getConfigKey('mapZoom').then((response) => {
          this.map.setZoom(parseInt(response.data.data));
        })

        


        this.map = L.map("map-container", {
          center: [this.mapCenter_lat, this.mapCenter_lng], // 中心位置
          //center: ['28.210508', '112.894302'], // 中心位置
          zoom: this.mapZoom, // 缩放等级
          attributionControl: false, // 版权控件
          zoomControl: true //缩放控件
        });
        console.log(2);
        //this.map = map1; // data上需要挂载
        L.tileLayer(
          //"http://localhost:1122?style=6&x={x}&y={y}&z={z}"
        //"https://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}" //在线
          mapUrl
        ).addTo(this.map); // 加载底图
         
        this.map.pm.setLang('zh');

        this.map.pm.addControls({
          position:'topleft',
          drawMarker:false,
          drawCircle:false,
          drawPolyline:false,
          drawCircleMarker:false,
          drawText:false,
          editMode:false,
          dragMode:false,
          cutPolygon:false,
          rotateMode:false,
        });

        this.map.on('pm:create',e=>{
          console.log(e.layer._latlngs);    
          var ss=e.layer._latlngs[0];
          const jsonString = JSON.stringify(ss);
          console.log(jsonString);
        
          this.form.pointListLatLng=jsonString;
          this.form.defenceAreaId=this.queryParams.id;
          addDrawPolygon(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              // this.open = false
              // this.getList()
          })
        });

        this.map.on("pm:remove", (e) => {
        //通过移除模式移除图层时触发
        console.log("1"+e);
        var ss=e.layer._latlngs[0];
        const jsonString = JSON.stringify(ss);
        console.log(jsonString);

        const Ids = jsonString;
        this.$confirm('是否确认删除雷达编号为"' + Ids + '"的数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        .then(function () {
          return delDrawPolygon(jsonString)
        })
        .then(() => {
          // this.getList()
          this.$modal.msgSuccess("删除成功")
        })
      });

        this.map.on("pm:globalremovalmodetoggled", (e) => {
        //点击开始/结束 删除时出发       
        
        //console.log("4"+e);
        });

      // this.map.on("layerremove", (e) => {
      //    //删除任何层时触发 
      // });
        //this.initAlarm();

        this.map.pm.setPathOptions({
          color: "red",
          fillColor: "red",
          fillOpacity: 0.1,
        });

      },
      initDrawPolygon(){
        listDrawPolygon().then(res => {
          if (res.data.code == 200) {     
            for (let index = 0; index < res.data.data.length; index++) {
              this.drawPolygon.push({drawidd:res.data.data[index].drawId,latlng:res.data.data[index].pointListLatLng});
            }             
            for (let index = 0; index < this.drawPolygon.length; index++) {
              var aa=JSON.parse(this.drawPolygon[index].latlng);
              L.polygon(aa,
                {
                  // 折线颜色（支持 HEX、RGB、颜色名称，如 'red'、'#ff0000'）
                    color: '#ff0000',
                    // 折线宽度（单位：像素）
                    weight: 2,
                    fill: true,      
                    // 填充颜色          
                    fillColor: '#ff0033',      
                    // 填充透明度（0 到 1）    
                    fillOpacity: 0.1,      
                }
              ).addTo(this.map);
            }         
          }
        })
      },
      initRadar()
      {
          this.radarDevice = new L.Radar({
          radius:this.radarDraw.radius,
          status:1,
          angle:this.radarDraw.angle,
          direction:this.radarDraw.northDeviationAngle,
          location:""+this.radarDraw.lat+" "+this.radarDraw.lng+""
          },{
            online: {
              color: '#dd2',
              dashArray: [5, 15],
              weight: 1,
              opacity: 1,
              fillColor: '#d21',
              fillOpacity: 0.1
            },
            animat: {
              color: '#dd2',
              weight: 1,
              opacity: 1,
              fillColor: "#d21",
              fillOpacity: 0.01,
              pmIgnore: true
            },
            step:this.radarDraw.step
          })
          this.radarDevice.addTo(this.map)

          this.radarDevices.push(this.radarDevice);

      },
      initAlarm(){
        window.chrome.webview.addEventListener('message', event => 
        {
          if(event.data.type=="refcenter")
          {
            mapCenter_lat=parseFloat(event.data.data[0].MapCenter_lat);
            mapCenter_lng=parseFloat(event.data.data[0].MapCenter_lng);
            var newLatLng = L.latLng(mapCenter_lat, mapCenter_lng);
            this.map.setView(newLatLng);
          }
          else if(event.data.type=="defencearea")
          {
            event.data.data.forEach(element => {
              lat = element.lat;
              lng = element.lng;
              radius=element.defenceradius;
              azimuthAngle=element.azimuthangle;
              angle=element.angle;
              step=parseInt(element.step) ;
              this.initRadar();
            });
          }
          else if(event.data.type=="mapset")
          {
            mapUrl= event.data.data[0].MapUrl;
            mapCenter_lat=parseFloat(event.data.data[0].MapCenter_lat);
            mapCenter_lng=parseFloat(event.data.data[0].MapCenter_lng);
            mapZoom= parseInt(event.data.data[0].MapZoom);
            var newLatLng = L.latLng(mapCenter_lat, mapCenter_lng);
            this.map.setZoom(mapZoom);
            this.map.setView(newLatLng);
          }
          else if(event.data.type=="alarm_record")
          {
            var t1=event.data.data
            var HseqGroup =L.motion.seq([
            L.motion.polyline(t1,
            {
            color: "orangered",
            weight: 5,
            }
            , 
            {
            easing: L.Motion.Ease.easeInOutQuad
            }
            , 
            {
            removeOnEnd: false,
            icon: L.divIcon({html: "<img src='./public/marker/marker-icon.png' class='leaflet-marker-icon lmap-icon leaflet-zoom-animated leaflet-interactive' alt='Marker' tabindex='0' role='button' style='margin-left: -14px; margin-top: -45px; width: 25; height: 41px;  z-index: 369;'>", iconSize: L.point(0, 0)})
            }
            ).motionDuration(10000),
            ]).addTo(this.map).motionStart();  
          }
          else if(event.data.type=="targetadd"){
            var curr_Target1=[];
            curr_Target1.push({lat:28.212469,lng: 112.894330})
            curr_Target1.push({lat:28.212469,lng: 112.804330})
            let shipPolyline1 =L.motion.polyline(curr_Target1).motionDuration();
            this.seqGroups[0].seqGroup.addLayer(shipPolyline1,true);
          }
          else
          { 
          }  
        });
      },
      clear_Target()
      {
        this.timer = setInterval(() => {       
          this.seqGroups.forEach((element,index,arr) => {
            var time_now=Date.now();
            var ss=time_now-element.timeClear;
            if(ss>1000)
            {
              this.map.removeLayer(element.seqGroup);
              this.seqGroups.splice(index,1);
            }
          });
        }, 1000);
      },
      clear_HisTarget()
      {
        this.timer = setInterval(() => {       
          this.his_seqGroups.forEach((element,index,arr) => {
            var time_now=Date.now();
            var ss=time_now-element.timeClear;
            if(ss>2000)
            {
              this.map.removeLayer(element.seqGroup);
              this.his_seqGroups.splice(index,1);
            }
          });
        }, 1000);
      },
      init(connection, api, acceptMsg, sendMsg,){
        this.connection = new signalR.HubConnectionBuilder()
          .withUrl(api, {})
          .withAutomaticReconnect([1000, 4000, 1000, 4000])// 断线自动重连
          .configureLogging(signalR.LogLevel.Error)
          .build()
        this.connection.on(acceptMsg, res => {
          console.log(acceptMsg, '获取数据：', res)
            this.serverData = JSON.parse(res);

          var targetid=this.serverData.targetId;
          var lat=this.serverData.lat;
          var lng=this.serverData.lng;

          var targetType="";
          switch (this.serverData.TargetType) {
            case 1:
                targetType="Human";
              break;
              case 2:
                targetType="Vehicle";
              break;
              case 3:
                targetType="Tree";
              break;
          
            default:
              targetType="Human";
            break;
          }

          var tt='[{"lat":'+lat+',"lng":'+lng+'},{"lat":'+lat+',"lng":'+lng+'}]'

          trackRoute=JSON.parse(tt) ;

          var ts= this.seqGroups.find(item => item.targetId == targetid);
          if(ts!=undefined)
          {
            this.map.removeLayer(ts.seqGroup);
          }

          this.seqGroup =L.motion.seq([
          L.motion.polyline(trackRoute
          ,{color: "orangered",weight: 7}, 
          {
          easing: L.Motion.Ease.easeInOutQuad
          ,duration: 3000,
          }, 
          {
          removeOnEnd: true,
          showMarker: true,
          icon: L.divIcon({html: "<div>&nbsp;ID:"+targetid+" type="+targetType+"</div>"
          , iconSize: L.point(0, 0),className: 'target-class'})
          }).motionDuration(1000),]).addTo(this.map).motionStart(10);  

          var time=Date.now();

          this.seqGroups.push({targetId:targetid,seqGroup: this.seqGroup,timeClear:time})
          

          //历史轨迹显示
          
          var ts= this.his_seqGroups.find(item => item.targetId == targetid);
          if(ts!=undefined)
          {     
            var shipPolyline1 = L.motion.polyline(trackRoute,{color: "orangered",weight: 2}).motionDuration(50);
            ts.seqGroup.addLayer(shipPolyline1);
          }
          else
          {
            this.his_seqGroup =L.motion.seq([
              L.motion.polyline(trackRoute
              ,{color: "orangered",weight: 2}).motionDuration(150),]).addTo(this.map).motionStart(10);          
          }

          //如果这个id的线条存在，就更新时间，否则加入      
          var time=Date.now();
          var ts= this.his_seqGroups.find(item => item.targetId == targetid);
          if(ts!=undefined){
            ts.timeClear=time;
          }else{
            this.his_seqGroups.push({targetId:targetid,seqGroup: this.his_seqGroup,timeClear:time})
          }
          
        })
        //自动重连成功后的处理
        this.connection.onreconnected((connectionId) => {
          console.log(connectionId, '自动重新连接成功')
        })
        // 开始
        if (this.connection.state !== signalR.HubConnectionState.Connected) {
          this.connection.start().then((res) => {
            console.log('启动即时通信成功')
            // this.connection.invoke()
          })
        }
        // 生命周期
        this.connection.onreconnecting(error => {
          console.log(acceptMsg, +'**', sendMsg, '重新连接ing', error)
          console.log(1)
          console.log(this.connection.state)
          console.log(this.connection.state === signalR.HubConnectionState.Reconnecting)
        })
        // (默认4次重连)，任何一次只要回调成功，调用
        this.connection.onreconnected(connectionId => {
          console.log('链接id', connectionId)
          console.log(2)
          console.log(this.connection.state)
          console.log(this.connection.state === signalR.HubConnectionState.Connected)
          if (this.connection.state === signalR.HubConnectionState.Connected) {
            console.log(acceptMsg, +'**', sendMsg, '重连')
            // this.connection.invoke()
          }
          // this.init()
        })
        this.connection.onclose(error => {
          console.log('关闭', error)
        })
      }
    },
    beforeDestroy() {
      // js提供的clearInterval方法用来清除定时器
      clearInterval(this.timer);
      
    }
  };
</script>
    
<style :scoped lang="scss">

  html, body, #app {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
  }
  
  .full-size {
    width: 100vw; /* 视口宽度 */
    height: 100vh; /* 视口高度 */
    overflow: hidden; /* 防止内容溢出 */
  }
  .target-class {
      color: red; /* 更改字体颜色为红色 */
  }
    ////////////////////@at-root
    /// 
  .div-canvas {
    width: 100vm;
    height: 100vh;
    //margin: 0px auto;
    background-color: #fffbfb2a; //#fff;
    //border: 3px;
    border-color: rgb(252, 248, 6);
    position: relative;
    background-color: aquamarine;
    overflow: hidden;
  }

  #imgCanvas,
  #pointCanvas,
  #radarCanvas {
    background: rgba(238, 23, 238, 0);
    position: absolute;
  }

  // .imgCanvas {
  //   z-index: 0;
  // }
  .pointCanvas {
    z-index: 2;
  }

  // .saveCanvas {
  //   z-index: 3;
  // }
  .tool-box {
    float: left;
    width: 100%;
    height: 30%;
    //   padding: 5px 10px;
    //   margin: 20px auto 0;
    box-sizing: border-box;
    text-align: left;
    background-color: aliceblue;
  }

  .slider-demo-block {
    display: flex;
    align-items: center;
  }
  .slider-demo-block .el-slider {
    margin-top: 0;
    margin-left: 12px;
  }
</style>


